import os
import json
import datetime
from flask import Flask, request, jsonify
import requests

app = Flask(__name__)

# 1. 企业微信机器人地址
WX_ROBOT_URL = os.getenv("WX_ROBOT_URL")  # 建议通过环境变量注入
if not WX_ROBOT_URL:
    raise RuntimeError("请设置环境变量 WX_ROBOT_URL 为企业微信机器人地址")

# 2. 白名单校验（可选）
WEBHOOK_TOKEN = os.getenv("GITLAB_WEBHOOK_TOKEN")  # 与 GitLab 中设置的 Secret Token 保持一致


def send_wxwork(markdown: str):
    """发送 markdown 消息到企业微信机器人"""
    resp = requests.post(WX_ROBOT_URL, json={"msgtype": "markdown", "markdown": {"content": markdown}}, timeout=5)
    resp.raise_for_status()

def send_wxwork_text(message: str):
    """发送 txt 消息到企业微信机器人"""
    resp = requests.post(WX_ROBOT_URL, json={"msgtype": "text", "text": {"content": message}}, timeout=5)
    resp.raise_for_status()


def build_push_msg(body):
    """组装 Push 事件消息"""
    project = body["project"]["name"]
    branch = body["ref"].split("/")[-1]
    user = body["user_name"]
    total = len(body["commits"])
    commits = "\n".join(
        f"> - [{c['id'][:8]}]({c['url']}) {c['message']}"
        for c in body["commits"][:5]
    )
    if total > 5:
        commits += "\n> - ..."
    return f"""\
**📌 Push 事件**  
> 项目：{project}  
> 分支：{branch}  
> 作者：{user}  
> 共 {total} 次提交：  
{commits}
"""


def build_mr_msg(body):
    """组装 Merge Request 事件消息"""
    attrs = body["object_attributes"]
    action = attrs["action"]  # open/merge/close/update
    title = attrs["title"]
    url = attrs["url"]
    author = body["user"]["name"]
    src = attrs["source_branch"]
    dst = attrs["target_branch"]
    if action == "open":
        action = "创建"
    elif action == "approved":
        action = "批准"
    elif action == "merge":
        action = "合并"
    return f"""\
**🔀 Merge Request {action}**  
> [{title}]({url})
> merge地址: {url}  
> 作者：{author}  
> 源分支：{src} → 目标分支：{dst}
"""



def build_issue_msg(body):
    """组装 Issue 事件消息"""
    attrs = body["object_attributes"]
    action = attrs["action"]
    title = attrs["title"]
    url = attrs["url"]
    author = body["user"]["name"]
    return f"""\
**📝 Issue {action}**  
> [{title}]({url})  
> 作者：{author}
"""


def build_tag_msg(body):
    """组装 Tag Push 事件消息"""
    tag = body["ref"].split("/")[-1]
    project = body["project"]["name"]
    user = body["user_name"]
    url = body["project"]["web_url"] + "/-/tags/" + tag
    return f"""\
**🏷️ Tag 创建**  
> [{project}:{tag}]({url})  
> 作者：{user}
"""


def build_pipeline_msg(body):
    """组装 Pipeline 事件消息"""
    project = body["project"]["name"]
    branch = body["object_attributes"]["ref"]
    status = body["object_attributes"]["status"]
    url = body["project"]["web_url"] + "/-/pipelines/" + str(body["object_attributes"]["id"])
    emoji = "✅" if status == "success" else ("❌" if status == "failed" else "⏳")
    return f"""\
**{emoji} Pipeline {status}**  
> 项目：{project}  
> 分支：{branch}  
> [查看详情]({url})
"""


EVENT_HANDLER = {
    "Push Hook": build_push_msg,
    "Merge Request Hook": build_mr_msg,
    "Issue Hook": build_issue_msg,
    "Tag Push Hook": build_tag_msg,
    "Pipeline Hook": build_pipeline_msg,
}


@app.route("/webhook/gitlab", methods=["POST"])
def gitlab_webhook():
    # # ===== 调试打印 =====
    # print("=== Headers ===")
    # for k, v in request.headers.items():
    #     print(f"{k}: {v}")
    # print("=== Body ===")
    # print(json.dumps(request.get_json(force=True), ensure_ascii=False, indent=2))

    # 1. 白名单校验
    if WEBHOOK_TOKEN and request.headers.get("X-Gitlab-Token") != WEBHOOK_TOKEN:
        return jsonify({"err": "Invalid token"}), 401

    # 2. 解析事件类型
    event = request.headers.get("X-Gitlab-Event")
    body = request.json
    if not body:
        return jsonify({"err": "empty body"}), 400
    # 3. 选择处理器并发送
    handler = EVENT_HANDLER.get(event)
    if handler:
        try:
            markdown = handler(body)
            if markdown:
                send_wxwork(markdown)
        except Exception as e:
            app.logger.exception("send wxwork failed")
            return jsonify({"err": str(e)}), 500

    return jsonify({"ok": True})


if __name__ == "__main__":
    # 本地调试：python gitlab_to_wxwork.py
    app.run(host="0.0.0.0", port=5000, debug=True)